import { GlobalConstant } from '@/library/constants/globalConstant'
import {
  type IRoutesItemLists,
  type AddSpecialPrefix,
} from './baseType'

/**
 * @param {string} str 分割字符串
 * @param {string} pathSeparator 字符传分隔符
 * @returns {Array}
 * @example
 * ```
 * generatePrefixPathArr('a.b.c')
 * return ['a', 'a.b', 'a.b.c']
 */
const generatePrefixPathArr = (str: string, pathSeparator = '.') => {
  const result = []
  const parts = str.split(pathSeparator)

  for (let i = 1; i <= parts.length; i++) {
    result.push(parts.slice(0, i).join(pathSeparator))
  }

  return result
}

/**
 * @function
 * @description 生成模块路由绝对路径
 * @param {string} basePagePath - page 模块路由
 * @param {Record<string, string>} subPath - 子路由map
 * @returns {TypeSubPath} 全模块路由绝对路径
 * @example
 * ```
    const basePagePath = 'd-c'
    const subPath = {
      demoOne: 'demo-one',
      demoTwo: 'demo-two',
      sourceCode: 'sourceCode',
      'sourceCode.one': 'one',
    }
    generatePagePath(basePagePath, subPath)
    {
      $$.demoOne: "d-c/demo-one"
      $$.demoTwo: "d-c/demo-two"
      $$.sourceCode: "d-c/sourceCode"
      $$.sourceCode.one: "d-c/sourceCode/one"
      basePagePath: "d-c"
      demoOne: "demo-one"
      demoTwo: "demo-two"
      sourceCode.one: "one"
    }
 * ```
 */

const generatePagePath = <T extends Record<string, string>>(basePagePath: string, subPath: T): AddSpecialPrefix<T> => (
  Object.keys(subPath).reduce((pre: any, next) => {
    pre[next] = subPath[next]
    const prefixPathArr = generatePrefixPathArr(next)
    const str = prefixPathArr.reduce((p, r) => `${p}/${subPath[r]}`, '')
    pre[`${GlobalConstant.PREFIX_FULLPATH}${next}`] = basePagePath + str
    return pre
  }, { basePagePath })
)

/**
 * @function
 * @description 模块默认index路由处理
 * @param {IRoutesItemLists} routeLists - page路由集合
 * @returns {IRoutesItemLists} 最终路由集合
 */
const generateRouteIndexPath = (routeLists: IRoutesItemLists): IRoutesItemLists => {
  if (routeLists && routeLists.length) {
    routeLists.forEach((route) => {
      const lists = route.children
      if (lists && lists.length) {
        const includeIndexItemLists = lists.filter((item) => item.index === true)
        if (includeIndexItemLists.length >= 1) {
          for (let i = 1; i < includeIndexItemLists.length; i += 1) {
            includeIndexItemLists[i].index = false
          }
        } else if (route.openDefaultIndex) {
          lists[0].index = true
        }
        for (let i = 0; i < lists.length; i += 1) {
          const child = lists[i]
          child.auth = child.auth ?? route.auth ?? false
          if (child.children && child.children.length) {
            generateRouteIndexPath([child])
          }
        }
      }
    })
  }
  return routeLists
}

export {
  generatePagePath,
  generateRouteIndexPath,
}
